package com.software.practicecenter.service;

import com.software.practicecenter.entity.Question;
import com.software.practicecenter.repository.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @Author xiaoliao
 * @Date 2023/5/31 14:40
 */
@Transactional
@Service
public class QuestionService {
    @Autowired
    private QuestionRepository questionRepository;

    public List<Question> findQuestionByBelongChapter(String chapter){

        return questionRepository.findQuestionByBelongChapter(chapter);
    }

    public List<Question> findByIdIn(Collection<String> ids) {
        return questionRepository.findByIdIn(ids);
    }


    public Question findQuestionById(String id) {
        return questionRepository.findQuestionById(id);
    }

    public Page<Question> findAll(Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        return questionRepository.findAll(pageable);
    }

    public Page<Question> findQuestionByBelongChapterAndQuestion(String belongChapter, String question, Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        Specification<Question> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (belongChapter != null && !belongChapter.isEmpty() && !belongChapter.equals("所有章节")) {
                predicates.add(cb.equal(root.get("belongChapter"), belongChapter));
            }
            if (question != null && !question.isEmpty()) {
                predicates.add(cb.like(root.get("question"), "%" + question + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return questionRepository.findAll(spec, pageable);
    }

    public Question addQuestion(Question question) {
        question.setId(UUID.randomUUID().toString());
        return questionRepository.save(question);
    }

    public Question updateQuestion(Question question) {
        return questionRepository.save(question);
    }

    public Question findById(String id) {
        Optional<Question> optional = questionRepository.findById(id);
        return optional.get();
    }

    public void deleteQuestionById(String id) {
        Question question = findById(id);
        questionRepository.delete(question);
    }
}
